package com.xxxcompany.wordbook.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.xxxcompany.wordbook.entity.User;
import com.xxxcompany.wordbook.service.IUserService;
import com.xxxcompany.wordbook.service.UserServiceImpl;

@WebServlet("/loginchk")
public class UserLoginCheckServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter pw = resp.getWriter();
		
		// 1. 
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		System.out.println(username+","+password);
		
		
		// 2
		IUserService userService = new UserServiceImpl();
		User user = userService.login(username, password);
		
		// 3.
		if(user!=null)
		{
			System.out.println("登录成功");
			// 在会话中保存登录状态
			HttpSession session = req.getSession();
			session.setAttribute("user", user);;
			
			resp.sendRedirect("user_index");
		}
		else
		{
			System.out.println("登录失败");
			resp.sendRedirect("login");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doGet(req, resp);
	}
}